# coding: utf-8
from datetime import datetime
from sqlalchemy import Column, String, DATETIME, ForeignKey, text, func
from sqlalchemy.dialects.mysql import INTEGER, TINYINT
from sqlalchemy.orm import relationship
from ..database import db,serialize
from .admin import Admin
from .roleuser import RoleUser

class Role(db.Model):
    __tablename__ = 'roles'

    id = Column(INTEGER(11), primary_key=True)
    name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False)
    status = Column(TINYINT(3), nullable=False, server_default=text("'1'"))
    created_at = Column(DATETIME, default=datetime.now())
    updated_at = Column(DATETIME, default=datetime.now(), server_default=func.now(), onupdate=func.now(), comment='修改时间')
    # 多对多用户
    admins = relationship('RoleUser', foreign_keys=[RoleUser.role_id], backref=db.backref('admins', lazy='joined'),lazy='dynamic')

    # 查出来所有关联的用户，单条查询还可以，循环太慢
    @property
    def admin(self):
        return Admin.query.join(RoleUser, RoleUser.user_id == Admin.id).filter(RoleUser.role_id == self.id)

    @staticmethod
    def toJson(roles):
        tmp = []
        for item in roles:
            tmp.append(
                {
                    'id': item.id,
                    'name': item.name,
                    'status': item.status,
                    'created_at': item.created_at,
                    'updated_at': item.updated_at,
                    # 'admins': {c.id: c.name for c in item.admin}
                }
            )
        return tmp

    
    def getPage(page = 1):
        lists = Role.query.order_by(Role.id.desc()).paginate(
            page, per_page=10, error_out=False)
        # 查出来的所有列 id
        role_ids = []
        for i in lists.query.values(Role.id):
            role_ids.append(i[0])
        # 找出来每个 role_id 中间对应的 user_id
        query_r_u = RoleUser.query.filter(RoleUser.role_id.in_(
            role_ids)).all()
        role_user = {}
        admin_ids = []
        for i in query_r_u:
            role_user.setdefault(i.role_id,[]).append(i.user_id)
            admin_ids.append(i.user_id)
        # 去重
        admin_ids = list(set(admin_ids))
        # 所有用户信息
        admins = Admin.query.filter(Admin.id.in_(admin_ids)).all()
        # 更简单的方法
        # a = Admin.query.join(RoleUser, RoleUser.user_id == Admin.id).filter(RoleUser.role_id.in_(role_ids)).all()
        admin_dict = {}
        for item in admins:
            admin_dict[item.id] = serialize(item)
        # 开始组合
        resdata = []
        for i in lists.items:
            # 找出来所有对应的 user_id
            tmp_ids = role_user.get(i.id, None)
            # 根据用户 id 生成用户信息字典
            tmp_admins = []
            if tmp_ids != None:
                for t in tmp_ids:
                    tmp_admins.append(admin_dict.get(t))
            # 插入返回值
            resdata.append(
                {
                    'id': item.id,
                    'name': item.name,
                    'status': item.status,
                    'created_at': item.created_at,
                    'updated_at': item.updated_at,
                    'admins': tmp_admins
                }
            )
        return {'count' : lists.total, 'lists' : resdata}

    
